/*
 * @Date         : 2024-05-20 11:40:00 星期1
 * @Author       : xut
 * @Description  :
 */
import { promisify } from "node:util"
import type { Request, Response } from "express"
import { authClient } from "../client"
import {
  RegisterUserInput,
  LoginUserInput,
  RefreshTokenInput,
  VerifyEmailInput,
} from "../schema/auth.schema"

const grpcRegister = promisify(authClient.signUpUser).bind(authClient)
const grpcLogin = promisify(authClient.signInUser).bind(authClient)
const grpcRefreshToken = promisify(authClient.refreshToken).bind(authClient)
const grpcVerifyEmail = promisify(authClient.verifyEmail).bind(authClient)

export async function register(
  req: Request<{}, {}, RegisterUserInput>,
  res: Response
) {
  try {
    const { name, email, password, photo } = req.body
    const data = grpcRegister({ name, email, password, photo })
    return res.status(201).json(data)
  } catch (err: any) {
    return res.status(400).json({
      status: "fail",
      message: err.message,
    })
  }
}

export async function login(
  req: Request<{}, {}, LoginUserInput>,
  res: Response
) {
  try {
    const { email, password } = req.body
    const data = grpcLogin({ email, password })
    return res.status(200).json(data)
  } catch (err: any) {
    return res.status(400).json({
      status: "fail",
      message: err.message,
    })
  }
}

export async function refreshToken(
  req: Request<{}, {}, RefreshTokenInput>,
  res: Response
) {
  try {
    const { refresh_token } = req.body
    const data = grpcRefreshToken({ refresh_token })
    return res.status(200).json(data)
  } catch (err: any) {
    return res.status(400).json({
      status: "fail",
      message: err.message,
    })
  }
}

export async function verifyEmail(
  req: Request<{}, {}, {}, VerifyEmailInput>,
  res: Response
) {
  try {
    const data = grpcVerifyEmail({
      verification_code: req.query.verification_code,
    })
    return res.status(200).json(data)
  } catch (err: any) {
    return res.status(400).json({
      status: "fail",
      message: err.message,
    })
  }
}
